const router = require("koa-router")();

/**
 *
 * api {get} /home/app/plugins/mail 获取邮件配置
 *
 */
router.get("/mail", async (ctx, nex) => {
  const baas = ctx.baas;
  const mail = await BaaS.Models.plugins_mail
    .query({ where: { baas_id: baas.id } })
    .fetch();
  ctx.success(mail);
});
/**
 *
 * api {get} /home/app/plugins/mail/add 提交邮件配置
 *
 */
router.post("/mail/add", async (ctx, nex) => {
  const baas = ctx.baas;
  const {
    host = "",
    secureConnection = "",
    port = "",
    user = "",
    pass = ""
  } = ctx.post;

  const mailConfig = await BaaS.Models.plugins_mail
    .query({ where: { baas_id: baas.id } })
    .fetch();
  const id = mailConfig.id;
  // 验证表单是否为空
  const isEmpty = ctx.isEmpty(
    {
      host: host,
      secureConnection: secureConnection,
      port: port,
      user: user,
      pass: pass
    },
    ["host", "secureConnection", "port", "user", "pass"]
  );
  if (!isEmpty) {
    ctx.error("请完善表单");
    return;
  }
  const mail = await BaaS.Models.plugins_mail
    .forge({
      id: id,
      baas_id: baas.id,
      host: host,
      secureConnection: secureConnection,
      port: port,
      user: user,
      pass: pass
    })
    .save();
  ctx.success(mail);
});

module.exports = router;
